<script setup lang="ts">
  import { PropType, ref, watch } from 'vue'
  import useUpdateFreePercentageByNetworkIdsService from '@/services/pages/network/useUpdateFreePercentageByNetworkIdsService'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { FormInstance } from 'element-plus'

  const { updateForm, updateLoading, update, resetUpdateForm } =
    useUpdateFreePercentageByNetworkIdsService()

  defineOptions({
    name: 'MultipleUpdateFreePercentageModal',
  })

  const props = defineProps({
    networkIds: {
      type: Array as PropType<Array<string>>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  const visible = defineModel<boolean>('modelValue', { default: false })
  const rules = {
    freeAmountPercentage: [{ required: true, message: '请输入免费金额比例', trigger: 'blur' }],
  }
  const formInstance = ref<FormInstance | null>(null)

  const hideDialog = () => {
    resetUpdateForm()
    visible.value = false
  }

  const onConfirmClick = async () => {
    if (formInstance.value) {
      try {
        await formInstance.value.validate()
        const res = await update()
        if (res) {
          if (res.code === 20000) {
            HMessage.success('操作成功')
            emits('update')
            hideDialog()
            return
          }

          HMessageBox.error(res.message)
          return
        }

        HMessageBox.error('修改失败，请稍后重试')
      } catch (error) {
        // error
      }
    }
  }

  watch(visible, (value) => {
    if (value) {
      updateForm.value.networkIds = props.networkIds
    }
  })
</script>

<template>
  <h-dialog v-model="visible" title="批量修改免费额度比例" :loading="updateLoading">
    <el-form
      ref="formInstance"
      inline-message
      label-position="top"
      class="modal_form_content"
      :model="updateForm"
      :rules="rules"
    >
      <el-form-item label="免费额度比例" prop="freeAmountPercentage">
        <el-input v-model.trim="updateForm.freeAmountPercentage" placeholder="请输入免费额度比例" />
      </el-form-item>
    </el-form>

    <template #footer>
      <h-button is-modal type="primary" @click="onConfirmClick">确定</h-button>
      <h-button is-modal @click="hideDialog">取消</h-button>
    </template>
  </h-dialog>
</template>
